<template>
   <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <div style="margin-bottom:15px;text-align:right">
          <!-- <a-input
            placeholder="code码"
            v-model="ccode"
            allowClear
            style="width:230px;float:left;margin-right:10px"
          /> -->
          <a-select
            placeholder="选择状态"
            style="width:230px;float:left;margin-right:10px"
            :allowClear='true'
            @change="handleChange"
          >
            <a-select-option
              v-for="(item,i) in arr"
              :key="i"
              :value="item.key"
            >
              {{item.name}}
            </a-select-option>

          </a-select>
          <a-button
            type='primary'
            style="float:left"
            @click="search"
          >搜索</a-button>

          <a-button
           v-action:add
            icon="plus"
            type='primary'
            @click="addrole"
          >新增</a-button>
        </div>
      </div>

      <a-table
        :columns="columns"
        :data-source="datalist"
        :rowKey='record=>record.id'
        :pagination="true"
        :loading="loading"
      >
        <template
          slot="status"
          slot-scope="text,record"
        >
          <a-switch
           v-action:changeStatus
            :checked=buer[text]
            @change="offset(record)"
            checked-children="启用"
            un-checked-children="未启用"
          />
        </template>
        <template
          slot="操作"
          slot-scope="text, record"
        >
 
          <a
           v-action:edit
            href="javascript:;"
            style="margin-left:20px"
            @click="bianji(record)"
          >编辑</a>
          <a-popconfirm
            style="margin-left:20px"
            cancelText='取消'
            okText="确认"
            title="您确定要删除吗?"
            @confirm="onDelete(record)"
          >
            <a  v-action:del href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </a-table>
       <!-- <a-pagination show-quick-jumper :defaultPageSize='1'  :current='yeshu' :total="totalnum" @change="onChange1" style=" margin-top:15px;text-align:right" /> -->

    <!-- 新增 -->
    <a-modal
      :title="usertitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      :destroyOnClose='true'
      cancel-text="取消"
      ok-text="确定"
    >
      <a-form
        :form="form"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
        @submit="handleOk"
      >
        <a-form-item label="名称：">
          <a-input
            placeholder="请输入名称："
            v-decorator="['name', { rules: [{ required: true, message: '请输入名称：' }] }]"
          />
        </a-form-item>
        <a-form-item label="code">
          <a-input
            placeholder="请输入code"
            v-decorator="['code', { rules: [{ required: true, message: '请输入code' }] }]"
          />
        </a-form-item>
        <a-form-item label="排序">
          <a-input
            placeholder="请输入排序"
            v-decorator="['orderNum', { rules: [{ required: true, message: '请输入排序' }] }]"
          />
        </a-form-item>

        <div
          class="flex_list"
          v-for="(k, index) in form.getFieldValue('keys')"
          :key="k"
        >
          <div class="title_name">子级{{index+1}}</div>
          <a-form-item
            label="名称"
            class="flex_list1"
          >
            <a-input
              placeholder="请输入名称"
              v-decorator="[`dictLabel[${k}]`, { rules: [{ required: true, message: '请输入名称' }] }]"
            />
          </a-form-item>
          <a-form-item
            label="value"
            class="flex_list1"
          >
            <a-input
              placeholder="请输入value"
              v-decorator="[`value[${k}]`, { rules: [{ required: true, message: '请输入value' }] }]"
            />
          </a-form-item>
          <a-form-item
            label="排序"
            class="flex_list1"
            style="margin-bottom:0"
          >
            <a-input
              placeholder="请输入排序"
              v-decorator="[`orderNumS[${k}]`, { rules: [{ required: true, message: '请输入排序' }] }]"
            />
          </a-form-item>
          <a-icon
            v-if="form.getFieldValue('keys').length > 1"
            class="dynamic-delete-button"
            type="minus-circle-o"
            :disabled="form.getFieldValue('keys').length === 1"
            @click="() => remove(k)"
          />
        </div>
        <a-form-item
          label=" "
          style="text:center"
        >
          <a-button
            type="primary"
            size='large'
            @click="addwuzi"
            style="min-width:140px"
          >
            继续添加
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
    </a-card>

   </page-header-wrapper>
</template>

<script>
import {
  getlist,
  sava,
  deletedata,
  queryByTypeCodeList,
  editstatus,
} from "@/api/datadictionary";
import { forEach } from "store/storages/all";

const columns = [
  {
    title: "创建时间",
    dataIndex: "createTime",
    align: "center",
  },
  {
    title: "角色名称",
    dataIndex: "name",
    align: "center",
  },
  {
    title: "code码",
    dataIndex: "code",
    align: "center",
  },

  {
    title: "状态",
    dataIndex: "status",
    align: "center",
    scopedSlots: { customRender: "status" },
  },
  {
    title: "操作",
    dataIndex: "operation",
    scopedSlots: { customRender: "操作" },
    align: "center",
  },
];
let id = 0;

export default {
  name: 'datadictionary',
  data() {
    return {
      loading:false,
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 24, offset: 0 },
        },
        query: "",
      },
      arr: [
        { name: "未启用", key: "0" },
        { name: "启用", key: "1" },
      ],
      ccode: "",
      zhuangtai: "",
      fenpei: "",
      columns,
      datalist: [],
      totalnum: 0,
      yeshu: 1,
      usertitle: "",
      confirmLoading: false,
      visible: false,
      confirmLoading1: false,
      visible1: false,
      buer: [false, true],
      bianjiid: "",
      user: [],
      caidan: [],
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "coordinated" });
    this.form.getFieldDecorator("keys", { initialValue: [], preserve: true });
  },
  mounted() {
    this.getlist(1);
  },
  methods: {
    handleChange(value) {
      this.zhuangtai = value;
      console.log(this.zhuangtai);
    },
    getlist(val) {
      this.loading = true
      new Promise((resolve, reject) => {
        getlist({
          pageNo: val,
          pageSize: 10,
          code: this.ccode,
          status: this.zhuangtai,
        })
          .then((response) => {
            if (response.code == 0) {
              this.datalist = response.data.records;
              this.totalnum = response.data.pages;
            } else {
              this.$notification.error({
                message: "失败",
                description: response.msg,
              });
            }
            resolve();
          })
          .catch((error) => {
            // this.$notification.error({
            //   message: "失败",
            //   description: `获取失败`,
            // });
            reject(error);
          });
      });
      this.loading = false
    },
    onChange1(pageNumber) {
      this.yeshu = pageNumber;
      this.getlist(this.yeshu);
    },

    search() {
      console.log(this.ccode);
      console.log(this.zhuangtai);
      this.getlist(1);
    },
    //动态添加
    addwuzi() {
      const { form } = this;
      console.log(form);
      // can use data-binding to get
      const keys = form.getFieldValue("keys");
      console.log(keys);
      const nextKeys = keys.concat(id++);
      // can use data-binding to set
      // important! notify form to detect changes
      form.setFieldsValue({
        keys: nextKeys,
      });
    },
    //动态删除
    remove(k) {
      console.log(k);
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue("keys");
      console.log(keys);
      // We need at least one passenger
      if (keys.length === 1) {
        return;
      }
      // can use data-binding to set
      form.setFieldsValue({
        keys: keys.filter((key) => key !== k),
      });
      console.log(form);
    },
    //改变状态
    offset(val) {
      console.log(val);
      let m;
      if (val.status) {
        m = 0;
      } else {
        m = 1;
      }
      new Promise((resolve, reject) => {
        editstatus({ id: val.id, status: m })
          .then((response) => {
            console.log(response);
            if (response.code == 0) {
              this.getlist(this.yeshu);
            } else {
              this.$notification.error({
                message: "失败",
                description:response.msg,
              });
            }
            resolve();
          })
          .catch((error) => {
            // this.$notification.error({
            //   message: "失败",
            //   description: `获取失败`,
            // });
            reject(error);
          });
      });
    },
    //新增
    addrole() {
      this.usertitle = "新增数据字典";
      this.visible = true;
      id = 0;
      console.log(this.form.getFieldValue("keys"));
      this.addwuzi();
      this.bianjiid = "";
    },

    //编辑
    bianji(val) {
      console.log(val);
      this.usertitle = "编辑数据字典";
      this.bianjiid = val.id;
      new Promise((resolve, reject) => {
        queryByTypeCodeList({ code: val.code })
          .then((response) => {
            console.log(response);
            if (response.code == 0) {
              this.visible = true;
              this.duqu(val, response.data);
            } else {
              this.$notification.error({
                message: "失败",
                description: response.msg,
              });
            }
            resolve();
          })
          .catch((error) => {
            this.$notification.error({
              message: "失败",
              description: `删除失败`,
            });
            reject(error);
          });
      });
    },
    //读取数据
    duqu(val, list) {
      id = 0;
      console.log(val, list);
      let dictLabel = [];
      let value = [];
      let orderNumS = [];
      list.forEach((item, i) => {
        dictLabel.push(item.dictLabel);
        value.push(item.dictValue);
        orderNumS.push(item.orderNum);
        console.log(i);
        this.addwuzi();
      });
      this.$nextTick(() => {
        this.form.setFieldsValue({
          name: val.name,
          code: val.code,
          orderNum: val.orderNum,
          dictLabel: dictLabel,
          value: value,
          orderNumS: orderNumS,
        });
      });
    },
    //删除
    onDelete(val) {
      console.log(val);

      new Promise((resolve, reject) => {
        deletedata({ id: val.id })
          .then((response) => {
            console.log(response);
            if (response.code == 0) {
              this.$notification.success({
                message: "成功",
                description: `删除成功`,
              });
              this.getlist(this.yeshu);
            } else {
              this.$notification.error({
                message: "失败",
                description: response.msg,
              });
            }
            resolve();
          })
          .catch((error) => {
            this.$notification.error({
              message: "失败",
              description: `删除失败`,
            });
            reject(error);
          });
      });
    },
    handleOk(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        console.log(values);

        if (!err) {
          let data = {
            name: values.name,
            code: values.code,
            orderNum: values.orderNum,
            dictDateList: [],
            id: this.bianjiid,
          };

          values.orderNumS.forEach((item, i) => {
            data.dictDateList.push({
              dictLabel: values.dictLabel[i],
              value: values.value[i],
              orderNum: item,
            });
          });
          data.dictDateList = JSON.stringify(data.dictDateList);
          console.log(data);
          this.confirmLoading = true;
          new Promise((resolve, reject) => {
            sava(data)
              .then((response) => {
                if (response.code == 0) {
                  console.log(response);
                  this.$notification.success({
                    message: "成功",
                    description: "新增成功",
                  });
                  this.getlist(1);
                  this.confirmLoading = false;
                  this.visible = false;
                  this.$nextTick(() => {
                    this.form.setFieldsValue({
                      keys: [],
                    });
                  });
                } else {
                  this.confirmLoading = false;
                  this.$notification.error({
                    message: "失败",
                    description: response.msg,
                  });
                }
                resolve();
              })
              .catch((error) => {
                this.confirmLoading = false;
                this.$notification.error({
                  message: "失败",
                  description: `新增失败`,
                });
                reject(error);
              });
          });
        }
      });
    },

    //取消弹窗
    handleCancel(e) {
      this.visible = false;
      this.confirmLoading = false;
      this.visible1 = false;
      this.confirmLoading1 = false;
      console.log(this.form.getFieldValue("keys"));
      this.$nextTick(() => {
        this.form.setFieldsValue({
          keys: [],
        });
      });
    },
  },
};
</script>

<style scoped>
.flex_list {
  border-top: 1px solid #ccc;
  padding-top: 24px;
  position: relative;
}
.title_name {
  position: absolute;
  font-size: 16px;
  width: 100px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  top: -20px;
  left: 50%;
  margin-left: -50px;
  font-weight: bold;
  background: #fff;
}
.structure_cent {
  background: #fff;
  border: 1px solid #ccc;
}
.structure_cent_title {
  width: 100%;
  font-size: 16px;
  color: #333;
  background: #f6f6f6;
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  border-bottom: 1px solid #ccc;
}
.structure_cent_title span {
  border-left: 4px solid #0086ff;
  padding-left: 15px;
}
.structure_cent_b {
  max-width: 1200px;
  margin: auto;
  padding-top: 60px;
  padding-bottom: 60px;
}
.structure_cent_b_left {
  width: 300px;
  border: 1px solid #ccc;
}
.structure_cent_b_right {
  width: 800px;
}
.structure_cent_b_title {
  margin-bottom: 30px;
}
.addbtn_f {
  width: 400px;
  display: flex;
  justify-content: space-between;
}
.addbtn_f div {
  width: 100px;
  height: 35px;
  border: 1px solid #ccc;
  text-align: center;
  line-height: 35px;
  font-size: 13px;
  color: #333;
  cursor: pointer;
  background: #f2f2f2;
}

.addbtn_f div:hover {
  background: #0086ff;
  color: #fff;
}
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: -30px;
  right: -350px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #0086ff;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>